﻿using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace NRank.Common
{
	/// <summary>
	/// Creates associative field list using hashtable. Enables adding and accessing items based 
	/// on some hash value.
	/// </summary>
	/// <typeparam name="TField">Type of hashed field</typeparam>
	/// <typeparam name="TItem">Type of stored item</typeparam>
	public class AssociativeFieldList<TField, TItem>
	{
		/// <summary>
		/// Hash table with items
		/// </summary>
		private readonly Hashtable hashtable = new Hashtable(1024, (float) 0.6);

		/// <summary>
		/// Adds item to table
		/// </summary>
		/// <param name="field">Item's hashed field</param>
		/// <param name="item">Item to be added</param>
		public void Add(TField field, TItem item)
		{
			if (hashtable.ContainsKey(field))
			{
				var list = hashtable[field] as List<TItem>;
				list.Add(item);
			}
			else
			{
				hashtable.Add(field, new List<TItem> {item});
			}
		}

		/// <summary>
		/// Indexer for easy access
		/// </summary>
		/// <param name="field">Hash value</param>
		/// <returns>Items with given hash</returns>
		public IEnumerable<TItem> this[TField field]
		{
			get
			{
				var list = hashtable[field] as List<TItem>;
				if (list == null) return Enumerable.Empty<TItem>();

				return list;
			}
		}
	}
}